package com.xgr.wonderful.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.fb.FeedbackAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.AboutAppActivity;
import com.xgr.wonderful.activity.AdActivity;
import com.xgr.wonderful.activity.MyInfoModifyActivity;
import com.xgr.wonderful.activity.UploadAvatarActivity;
import com.xgr.wonderful.activity.base.BaseHomeFragment;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.sns.SharePopWindow;
import com.xgr.wonderful.utils.ActivityManagerUtils;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.view.CircleImageView;

public class SettingsFragment extends BaseHomeFragment{
	private EMChatOptions mOptions;

	private Button mLogoutBtn;
	private RelativeLayout mUpdateApp;
	private RelativeLayout mAboutApp ;
	private RelativeLayout mShareApp;
	private RelativeLayout mFeedback;
	private CircleImageView mUserAvatar;
	private TextView mUsername;
	private TextView mUserId  ;
	private RelativeLayout mUserAvatarLayout  ; 
	private RelativeLayout mUsernameLayout ;
	private RelativeLayout mUserIdLayout ;

	private RelativeLayout mPushLayout ;
	private RelativeLayout mMsgGetLayout ;
	private RelativeLayout mMsgGetSoundLayout;
	private RelativeLayout mMsgGetVibLayout ;
	private LinearLayout mMsgGetDetailLayout; 
	
	private ImageView mPushOn ;
	private ImageView mPushOff ;
	private ImageView mMsgGetOn ;
	private ImageView mMsgGetOff ;
	private ImageView mSoundOn ;
	private ImageView mSoundOff ;
	private ImageView mVibrateOn;
	private ImageView mVibrateOff ;

	//private ActionBar mActionBar ;
	
	private MyClickListener myClickListener ;
	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.fragment_settings;
	}

	@Override
	protected void findViews(View view) {
		mUsernameLayout = (RelativeLayout)view.findViewById(R.id.setting_username_layout) ;
		mUserAvatarLayout = (RelativeLayout)view.findViewById(R.id.setting_useravatar_layout) ;
		mUserAvatar = (CircleImageView)view.findViewById(R.id.setting_useravatar);
		mUsername = (TextView)view.findViewById(R.id.setting_username);
		mUserId = (TextView)view.findViewById(R.id.setting_userid) ;
		mUserIdLayout= (RelativeLayout)view.findViewById(R.id.setting_userid_layout) ;
		
	    mPushLayout = (RelativeLayout)view.findViewById(R.id.setting_push_layout) ;
	    mMsgGetLayout = (RelativeLayout)view.findViewById(R.id.setting_msgget_layout) ;
	    mMsgGetSoundLayout = (RelativeLayout)view.findViewById(R.id.setting_msgget_sound_layout);
	    mMsgGetVibLayout = (RelativeLayout)view.findViewById(R.id.setting_msgget_vibrate_layout) ;
	    mMsgGetDetailLayout = (LinearLayout)view.findViewById(R.id.setting_msgget_detail_ll) ;
	    
	    mPushOff = (ImageView)view.findViewById(R.id.setting_push_swith_off) ;
	    mPushOn = (ImageView)view.findViewById(R.id.setting_push_swith_on) ;
	    mMsgGetOff = (ImageView)view.findViewById(R.id.setting_msgget_switch_off) ;
	    mMsgGetOn= (ImageView)view.findViewById(R.id.setting_msgget_switch_on) ;
	    mSoundOff= (ImageView)view.findViewById(R.id.setting_msgget_sound_off) ;
	    mSoundOn= (ImageView)view.findViewById(R.id.setting_msgget_sound_on) ;
	    mVibrateOff = (ImageView)view.findViewById(R.id.setting_msgget_vibrate_off) ;
	    mVibrateOn = (ImageView)view.findViewById(R.id.setting_msgget_vibrate_on) ;
	    
		mFeedback = (RelativeLayout)view.findViewById(R.id.setting_feedback_layout);
		mShareApp = (RelativeLayout)view.findViewById(R.id.setting_shareapp_layout);
		mUpdateApp = (RelativeLayout)view.findViewById(R.id.setting_update_layout);
		mAboutApp = (RelativeLayout)view.findViewById(R.id.setting_aboutapp_layout) ;
		mLogoutBtn = (Button) view.findViewById(R.id.setting_logout_btn);
	}

	@Override
	protected void setupViews(Bundle bundle) {
		mOptions = EMChatManager.getInstance().getChatOptions();
		
		myClickListener = new MyClickListener() ;
		
		if (LocalUserUtils.getInstance().getLocalUserName()!= null){
			mUsername.setText(LocalUserUtils.getInstance().getLocalUserName()) ;
		}
		if (LocalUserUtils.getInstance().getLocalUserID()!= null){
			mUserId.setText(String.valueOf(LocalUserUtils.getInstance().getLocalUserID())+"") ;
		}
		if(LocalUserUtils.getInstance().getLocalUser()!= null &&
				LocalUserUtils.getInstance().getLocalUser().getPhoto()!= null &&
				LocalUserUtils.getInstance().getLocalUser().getPhoto().getSmall()!= null){
			ImageLoader.getInstance().displayImage(
					LocalUserUtils.getInstance().getLocalUserPhoto().getSmall(),  
					mUserAvatar) ;
		} //否则 不用管
		// umeng推送
		if (sputil.isGetPush()){
			mPushOn.setVisibility(View.VISIBLE) ;
			mPushOff.setVisibility(View.INVISIBLE) ;
		}else {
			mPushOn.setVisibility(View.INVISIBLE) ;
			mPushOff.setVisibility(View.VISIBLE) ;
		}
		//聊天 信息相关的
		if(sputil.isGetAlert()){
			mMsgGetOff.setVisibility(View.INVISIBLE) ;
			mMsgGetOn.setVisibility(View.VISIBLE) ;
			mMsgGetDetailLayout.setVisibility(View.VISIBLE) ;
		}else {
			mMsgGetOff.setVisibility(View.VISIBLE) ;
			mMsgGetOn.setVisibility(View.INVISIBLE) ;
			mMsgGetDetailLayout.setVisibility(View.GONE) ;
		}
		if (sputil.isSoundAlert()){
			mSoundOff.setVisibility(View.INVISIBLE) ;
			mSoundOn.setVisibility(View.VISIBLE) ;
		}else {
			mSoundOff.setVisibility(View.VISIBLE) ;
			mSoundOn.setVisibility(View.INVISIBLE) ;
		}
		if (sputil.isVibrateAlert()){
			mVibrateOff.setVisibility(View.INVISIBLE) ;
			mVibrateOn.setVisibility(View.VISIBLE) ;
		}else {
			mVibrateOff.setVisibility(View.VISIBLE) ;
			mVibrateOn.setVisibility(View.INVISIBLE) ;
		}
		
	}
	
	@Override
	public void onResume() {
		// 用户名修改后刷新,还可以使用onActivityResult
		if (LocalUserUtils.getInstance().getLocalUserName()!= null){
			mUsername.setText(LocalUserUtils.getInstance().getLocalUserName()) ;
		}
		super.onResume();
	}

	@Override
	protected void setListener() {
		mLogoutBtn.setOnClickListener(myClickListener) ;
		mUpdateApp.setOnClickListener(myClickListener );
		mAboutApp.setOnClickListener(myClickListener) ;
		mShareApp.setOnClickListener( myClickListener) ;
		mFeedback.setOnClickListener(myClickListener) ;
		mUserAvatar.setOnClickListener(myClickListener);
		mUsername.setOnClickListener(myClickListener) ;
		mUserAvatarLayout.setOnClickListener(myClickListener) ;
		mUserAvatar.setOnClickListener(myClickListener) ;
		mUsernameLayout.setOnClickListener(myClickListener) ;
		mUserIdLayout.setOnClickListener(myClickListener) ;
		//消息相关的设置监听 
		mPushLayout.setOnClickListener(myClickListener );
		mMsgGetLayout.setOnClickListener(myClickListener) ;
		mMsgGetSoundLayout.setOnClickListener(myClickListener) ;
		mMsgGetVibLayout.setOnClickListener(myClickListener) ;
		
	}
	
	private class MyClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.setting_useravatar:
				//点击头像图片时情况 
				Intent intent4 = new Intent(mContext, UploadAvatarActivity.class) ;
				startActivity(intent4) ;
				break;
			case R.id.setting_useravatar_layout:
				//这里用来修改用户头像
				Intent intent1 = new Intent(mContext, UploadAvatarActivity.class) ;
				startActivity(intent1) ;
				break;
			case R.id.setting_username:
				//点击文字时情况
				Intent intent5= new Intent(mContext, MyInfoModifyActivity.class) ;
				startActivity(intent5) ; 
				break ;
			case R.id.setting_username_layout:
				//更改用户名
				Intent intent2= new Intent(mContext, MyInfoModifyActivity.class) ;
				startActivity(intent2) ; 
				break ;
			case R.id.setting_push_layout:
				if (mPushOn.getVisibility()== View.VISIBLE){
					mPushOn.setVisibility(View.INVISIBLE) ;
					mPushOff.setVisibility(View.VISIBLE) ;
					sputil.setGetPush(false) ;
					PushAgent.getInstance(mContext).disable() ;
				}else {
					mPushOn.setVisibility(View.VISIBLE) ;
					mPushOff.setVisibility(View.INVISIBLE) ;
					sputil.setGetPush(true) ;
					PushAgent.getInstance(mContext).enable() ;
				}
				ToastFactory.getToast(mContext,sputil.isGetPush() ? "接受":"不接受" ).show() ;
				break ;
			case R.id.setting_msgget_layout:
				if (mMsgGetOn.getVisibility() == View.VISIBLE){
					mMsgGetOn.setVisibility(View.INVISIBLE) ;
					mMsgGetOff.setVisibility(View.VISIBLE) ;
					mMsgGetDetailLayout.setVisibility(View.GONE) ;
					sputil.setGetAlert(false) ;
					mOptions.setNotifyBySoundAndVibrate(false) ;
					mOptions.setShowNotificationInBackgroud(false) ;
					mOptions.setNoticeBySound(false) ;
					mOptions.setNoticedByVibrate(false);
				}else {
					mMsgGetOn.setVisibility(View.VISIBLE) ;
					mMsgGetOff.setVisibility(View.INVISIBLE) ;
					mMsgGetDetailLayout.setVisibility(View.VISIBLE) ;
					sputil.setGetAlert(true) ;
					mOptions.setNotifyBySoundAndVibrate(true) ;
					mOptions.setShowNotificationInBackgroud(true) ;
					mOptions.setNoticeBySound(sputil.isSoundAlert()) ;
					mOptions.setNoticedByVibrate(sputil.isVibrateAlert());
				}
				EMChatManager.getInstance().setChatOptions(mOptions) ;
				break ;
			case R.id.setting_msgget_sound_layout:
				if (mSoundOn.getVisibility() == View.VISIBLE){
					mSoundOn.setVisibility(View.INVISIBLE) ;
					mSoundOff.setVisibility(View.VISIBLE) ;
					sputil.setSoundAlert(false) ;
				}else {
					mSoundOn.setVisibility(View.VISIBLE) ;
					mSoundOff.setVisibility(View.INVISIBLE) ;
					sputil.setSoundAlert(true) ;
				}
				mOptions.setNoticedByVibrate(sputil.isSoundAlert()) ;
				EMChatManager.getInstance().setChatOptions(mOptions) ;
				break ;
			case R.id.setting_msgget_vibrate_layout:
				if (mVibrateOn.getVisibility() == View.VISIBLE){
					mVibrateOff.setVisibility(View.VISIBLE)  ;
					mVibrateOn.setVisibility(View.INVISIBLE) ;
					sputil.setVibrateAlert(false) ;
				}else {
					mVibrateOff.setVisibility(View.INVISIBLE)  ;
					mVibrateOn.setVisibility(View.VISIBLE) ;
					sputil.setVibrateAlert(true) ;
				}
				mOptions.setNoticedByVibrate(sputil.isVibrateAlert()) ;
				EMChatManager.getInstance().setChatOptions(mOptions) ;
				break ;
			case R.id.setting_feedback_layout:/**如果开发者回复 用户并提醒 ，在MainActivity中设置 agent.sync(); **/
				FeedbackAgent agent = new FeedbackAgent(mContext) ;
				agent.startFeedbackActivity() ;
				break ;
			case R.id.setting_shareapp_layout:
				SharePopWindow mShare = new SharePopWindow(mContext,
						"分享身边的精彩事，交身边的朋友", "微圈", "http://weitushare.com/weitu.html",
						null, BitmapFactory.decodeResource(getResources(),
								R.drawable.logo));
				mShare.showAtLocation(((Activity) mContext).getWindow().getDecorView(), 
						Gravity.BOTTOM, 0, 0);
				break ;
			case R.id.setting_update_layout:
				ToastFactory.getToast(mContext, "正在查看版本信息").show(); 
				forceUpdate() ;
				break ;
			case R.id.setting_aboutapp_layout:
				Intent intent3 = new Intent(mContext, AboutAppActivity.class) ;
				startActivity(intent3) ;
				break ;
			case R.id.setting_logout_btn:
				sputil.setLogin(false) ;
				//EMChatManager.getInstance().logout() ; //去除，这样更好的接收消息
				MyApplication.getInstance().exit() ;
				ActivityManagerUtils.getInstance().removeAllActivity();
				break ;

			default:
				break;
			}
		}
		
	}
		
	private void forceUpdate (){
		UmengUpdateAgent.setDefault() ;//除了第一次，以后 都 要调用 一下，重新设置
		UmengUpdateAgent.setUpdateAutoPopup(false) ;
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {

			@Override
			public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
				// TODO Auto-generated method stub
				switch (updateStatus) {
		        case UpdateStatus.Yes: // has update
		            UmengUpdateAgent.showUpdateDialog(mContext, updateInfo);
		            break;
		        case UpdateStatus.No: // has no update
		            Toast.makeText(mContext, "没有更新", Toast.LENGTH_SHORT).show();
		            break;
		        case UpdateStatus.NoneWifi: // none wifi
		            Toast.makeText(mContext, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
		            break;
		        case UpdateStatus.Timeout: // time out
		            Toast.makeText(mContext, "请检查网络", Toast.LENGTH_SHORT).show();
		            break;
		        }
			}
		});
		UmengUpdateAgent.forceUpdate(mContext) ;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    /**使用SSO授权必须添加如下代码 */
	    LogUtils.i(TAG, "sso handle");
	    UMSocialService mController = UMServiceFactory
	            .getUMSocialService(Constant.DESCRIPTOR) ;
	    UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}

}
